﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Core.Extensions;
using System.Linq;
using System.Collections.Generic;
using TyMES.Model.GetData;
using TyMES.ViewModel.GetData.ProductDataTemplatesVMs;
using TyMES.Model;
using TyMES.Communication.Request;
using TyMES.Communication;
using Microsoft.EntityFrameworkCore;
using DotLiquid;
using NJsonSchema.CodeGeneration;

namespace TyMES.GetData.Controllers
{
    [AuthorizeJwtWithCookie]
    [ActionDescription("_Model.ProductDataTemplates")]
    [ApiController]
    [Route("/api/GetData/ProductDataTemplates")]
    public partial class ProductDataTemplatesController : BaseApiController
    {
        [ActionDescription("Sys.Get")]
        [HttpGet("{id}")]
        public IActionResult Get(string id)
        {
            var vm = Wtm.CreateVM<ProductDataTemplatesVM>(id);
            return Ok(vm);
        }

        [ActionDescription("Sys.Create")]
        [HttpPost("[action]")]
        public async Task<IActionResult> Create(ProductDataTemplatesVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoAddAsync();
   
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }

        }

        [ActionDescription("Sys.Edit")]
        [HttpPut("[action]")]
        public async Task<IActionResult> Edit(ProductDataTemplatesVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoEditAsync(false);
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }
        }
                

        [HttpPost("BatchEdit")]
        [ActionDescription("Sys.BatchEdit")]
        public ActionResult BatchEdit(ProductDataTemplatesBatchVM vm)
        {
            if (!ModelState.IsValid || !vm.DoBatchEdit())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(vm.Ids.Count());
            }
        }

		[HttpPost("BatchDelete")]
        [ActionDescription("Sys.Delete")]
        public IActionResult BatchDelete(string[] ids)
        {
            var vm = Wtm.CreateVM<ProductDataTemplatesBatchVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = ids;
            }
            else
            {
                return Ok();
            }
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(ids.Count());
            }
        }

        [ActionDescription("Sys.DownloadTemplate")]
        [HttpGet("GetExcelTemplate")]
        public IActionResult GetExcelTemplate()
        {
            var vm = Wtm.CreateVM<ProductDataTemplatesImportVM>();
            var qs = new Dictionary<string, string>();
            foreach (var item in Request.Query.Keys)
            {
                qs.Add(item, Request.Query[item]);
            }
            vm.SetParms(qs);
            var data = vm.GenerateTemplate(out string fileName);
            return File(data, "application/vnd.ms-excel", fileName);
        }

        [ActionDescription("Sys.Import")]
        [HttpPost("Import")]
        public ActionResult Import(ProductDataTemplatesImportVM vm)
        {

            if (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData())
            {
                return BadRequest(vm.GetErrorJson());
            }
            else
            {
                return Ok(vm.EntityList.Count);
            }
        }


        [ActionDescription("查询啮合校验模板")]
        [HttpPost("SearchGMProductDataTemplates")]
        public IActionResult SearchGMProductDataTemplates(GMTemplatesRequest request)
        {
            try
            {
                if (request.StationCode != "2-AOP040-0")
                    return Ok(new GMTemplatesResponse(false, $"获取啮合模板信息异常，工位号异常,当前使用工位{request.StationCode}",null));
                var GMTemplates = DC.Set<ProductDataTemplates>().Where(x=>x.StationCode==request.StationCode).AsNoTracking().ToList();
                List<GMTemplate> Templates = new List<GMTemplate>();

                foreach (var GMTemplate in GMTemplates)
                {
                    GMTemplate template = new GMTemplate();
                    template.ID = GMTemplate.ID;
                    template.StationCode = GMTemplate.StationCode;
                    template.ParamCode = GMTemplate.ParamCode;
                    template.ParamCodeKey = GMTemplate.ParamCodeKey;
                    template.Uperlimit = GMTemplate.ParamRange1;
                    template.Lowerlimit = GMTemplate.ParamRange2;
                    if (GMTemplate.EnableStatus == "USED")
                        template.enable = true;
                    else template.enable = false;
                    template.sort = GMTemplate.Sort;
                    template.EquCode = GMTemplate.EquCode;

                    Templates.Add(template);
                }
                return Ok(new GMTemplatesResponse(true, $"获取啮合信息成功", Templates));
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }


        [ActionDescription("更新啮合校验模板")]
        [HttpPost("AddGMProductDataTemplates")]
        public IActionResult AddGMProductDataTemplates(GMTemplatesRequest request)
        {
            try
            {
                var template_exist = DC.Set<ProductDataTemplates>().Where(x => x.StationCode == "2-AOP040-0" && x.EquCode == request.EquCode && x.ParamCode == request.ParamCode && x.Sort == request.sort).FirstOrDefault();
                if (template_exist == null)
                {
                    ProductDataTemplates template = new ProductDataTemplates();
                    //新增
                    if (request.enable)
                        template.EnableStatus = "USED";
                    else
                        template.EnableStatus = "";
                    template.ParamCode = request.ParamCode;
                    template.Sort = request.sort;
                    template.EquCode = request.EquCode;
                    template.ParamCodeKey = request.ParamCodeKey;
                    template.StationCode = "2-AOP040-0";
                    template.TemplateCode = "model1";
                    template.ParamRange1 = request.Uperlimit;
                    template.ParamRange2 = request.Lowerlimit;
                    DC.Set<ProductDataTemplates>().Add(template);
                    DC.SaveChanges();
                    return Ok(new ResponseBase(true, $"已添加设备{request.EquCode}的齿轴物料编码{request.ParamCode}参数{request.ParamCodeKey}的校验模板"));

                }
                else
                {
                    //更新
                    if (request.enable)
                        template_exist.EnableStatus = "USED";
                    else
                        template_exist.EnableStatus = "";
                    template_exist.ParamRange1 = request.Uperlimit;
                    template_exist.ParamRange2 = request.Lowerlimit;
                    template_exist.Sort = request.sort;
                    DC.SaveChanges();
                    return Ok(new ResponseBase(true, $"已更新设备{request.EquCode}的齿轴物料编码{request.ParamCode}参数{request.ParamCodeKey}的校验模板"));
                }
            }
            catch (Exception ex)
            {
                return Ok(new ResponseBase(false, $"设备{request.EquCode}的齿轴物料编码{request.ParamCode}参数{request.ParamCodeKey}的校验模板更新异常：{ex.Message}"));
            }
        }
    }
}